<script lang="ts" setup>
import { reactive, toRefs, ref, watch } from "vue" // vue
import { getSJDdevotedApi, createSJDdevotedApi, upSJDdevotedApi, delDeJDdevotedApi } from "@/api/SZ/JDdevoted" // 接口
import { FormInstance, ElMessage, ElMessageBox } from "element-plus" // elment
import { getqueryTeamName } from "@/api/SZ/SZXxfy" // 接口
import { Search, Refresh } from "@element-plus/icons-vue" // 按钮图标
import { shortcuts } from "@/utils/dateSet"
import { usePagination } from "@/hooks/usePagination" // 分页器
// 缓存
defineOptions({
  name: "JDdevoted"
})
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]
const defaultTime = new Date(2000, 1, 1, 0, 0, 0)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination() // 分页器
const data = reactive<any>({
  searchData: {
    createTime: "", // 创建时间
    shopId: undefined // 店铺
  },
  formData: {}
})

const { searchData, formData } = toRefs(data)
// #region 查

const loading = ref(true)
const tableData = ref<any>([])

//
const tablelist = async () => {
  if (!searchData.value.createTime) {
    searchData.value.createTime = []
  }
  if (!searchData.value.stateTime) {
    searchData.value.stateTime = []
  }
  //
  await getSJDdevotedApi({
    ...searchData.value,
    pageNum: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    StartTime: new Date(searchData.value.createTime[0]).getTime() || "", // 时间
    EndTime: new Date(searchData.value.createTime[1]).getTime() || "" // 时间
  })
    .then((res: any) => {
      tableData.value = res.data.list
      paginationData.total = res.data.total
      loading.value = false
    })
    .catch(() => {
      tableData.value = []
    })
}
tablelist()

// 订单来源根据部门查团队
const queryTeamName = ref()
const TeamName = async () => {
  await getqueryTeamName().then((res: any) => {
    queryTeamName.value = res.data
  })
}
TeamName()
// #endregion

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
// 搜索
function handleSearch() {
  tablelist()
  console.log(searchData.value, "搜索")
}
// 重置
function resetSearch() {
  searchFormRef.value?.resetFields()
  handleSearch()
}
// #endregion

// #region 添加和修改框
const dialogVisible = ref(false)
const formRef = ref<FormInstance | null>(null)
const ids = ref(undefined) // 判断修改还是增加
// 新增
const XZorder = () => {
  dialogVisible.value = true
}
// 修改
const handleUpdate = (row: any) => {
  ids.value = row.name
  dialogVisible.value = true
  formData.value = JSON.parse(JSON.stringify(row)) // 赋值需要深拷贝
  formData.value.values = {
    id: Number(row.shopId),
    name: row.shopName
  }
}

// 清空form框
const clearValidate = () => {
  formRef.value?.resetFields()
}

// 清空对话框
const resetForm = () => {
  ids.value = undefined
  clearValidate()
  formData.value = {}
}
// 确定按钮
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (ids.value === undefined) {
        formData.value.shopId = formData.value.values.id
        formData.value.shopName = formData.value.values.name
        createSJDdevotedApi({
          ...formData.value
        }).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          tablelist()
        })
      } else {
        formData.value.shopId = formData.value.values.id
        formData.value.shopName = formData.value.values.name
        upSJDdevotedApi({
          ...formData.value
        }).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          tablelist()
        })
      }
    } else {
      return false
    }
  })
}
// 删除
const handleDelete = (row: any) => {
  console.log(row, "删除")
  ElMessageBox.confirm(`确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delDeJDdevotedApi({ id: row.id, manageName: row.manageName }).then(() => {
      ElMessage.success("删除成功")
      tablelist()
    })
  })
}

// #endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], tablelist, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card>
      <el-row justify="center" align="middle">
        <el-col>
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="createTime" label="时间">
              <el-date-picker
                v-model="searchData.createTime"
                type="datetimerange"
                range-separator="到"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :shortcuts="shortcuts"
                :default-time="defaultTime1"
              />
            </el-form-item>
            <el-form-item prop="shopId" label="店铺">
              <el-select
                v-model.trim="searchData.shopId"
                clearable
                filterable
                placeholder="请选择订单来源"
                style="width: 240px"
                value-key="id"
              >
                <el-option v-for="item in queryTeamName" :key="item.id" :label="item.name" :value="item.id + ''" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
              <el-button @click="XZorder">新增订单</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>

    <!-- 刷单明细 -->
    <el-card class="top">
      <div class="mxbox">
        <el-button type="primary" plain>退款处理</el-button>
      </div>
      <el-table :data="tableData" border ref="tableRef" v-loading="loading">
        <el-table-column prop="id" label="id" align="center" />
        <el-table-column prop="manageTime" label="操作时间" align="center" />
        <el-table-column prop="manageName" label="操作人" align="center" />
        <el-table-column prop="shopId" label="店铺id" align="center" />
        <el-table-column prop="shopName" label="店铺名称" align="center" />
        <el-table-column prop="dt" label="日期" align="center" />
        <el-table-column prop="amount" label="处理金额" align="center" />
        <el-table-column prop="refundCount" label="退单量" align="center" />
        <el-table-column prop="fullQuantity" label="全量订单" align="center" />
        <el-table-column fixed="right" label="操作" align="center" width="150">
          <template #default="scope">
            <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div class="pagination" style="margin-top: 20px">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="paginationData.total"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/修改 -->
    <el-dialog v-model="dialogVisible" @close="resetForm">
      <el-form ref="formRef" :model="formData" style="width: 308px" label-position="left">
        <el-form-item prop="dt" label="时间" label-width="100px">
          <el-date-picker v-model="formData.dt" type="datetime" :default-time="defaultTime" />
        </el-form-item>
        <el-form-item prop="amount" label="处理金额" label-width="100px">
          <el-input v-model="formData.amount" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="values" label="店铺id" label-width="100px">
          <el-select v-model.trim="formData.values" clearable filterable placeholder="请选择订单来源" value-key="id">
            <el-option v-for="item in queryTeamName" :key="item.id" :label="item.name" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item prop="refundCount" label="退单量" label-width="100px">
          <el-input v-model="formData.refundCount" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="fullQuantity" label="全量订单" label-width="100px">
          <el-input v-model="formData.fullQuantity" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="amountType" label="费用类型" label-width="100px">
          <el-select v-model="formData.amountType" clearable placeholder="请选择" style="width: 240px">
            <el-option :key="1" label="退款处理" value="退款处理" />
            <el-option :key="2" label="取消订单" value="取消订单" />
            <el-option :key="3" label="自主售后" value="自主售后" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.pagination {
  display: flex;
  justify-content: flex-end;
}
.widthsmall {
  width: 80%;
}
.top {
  margin-top: 20px;
}
.mxbox {
  display: flex;
  justify-content: space-between;
}
.mxboxRight {
  margin-right: 10%;
}
</style>
